
package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.oahc.bookreaderone.MainActivity;

import android.os.Environment;

public class FileUtil {

    /**
     * 复制asset资源文件到sd卡
     * 
     * @param in
     * @param filename
     * @return
     */
    public static boolean copyToFile(String filename) {
        FileOutputStream mFileOut;
        File mFile;
        mFile = new File(Constant.filePath + filename + Constant.dress);
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        if (initFilePath() == -1) {
            return false;
        } else if (initFilePath() == 1 && mFile.exists()) {// sd卡已经存在文件了
            return true;
        }

        if (!mFile.exists()) {
            try {
                InputStream in = MainActivity.getInstance().getAssets().open(filename+".txt");
                mFile.createNewFile();
                mFileOut = new FileOutputStream(mFile);
                byte[] bytes = new byte[in.available()];
                in.read(bytes);
                mFileOut.write(bytes);
                in.close();
                mFileOut.flush();
                mFileOut.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }

        return true;
    }

    /**
     * 初始化即将保存到的文件夹目录 status: -1失败 0新建成功 1已经新建
     */
    private static byte initFilePath() {
        byte status = -1;
        try {
            String mLastPath = Constant.filePath;
            File mLastFolder = new File(mLastPath);
            if (!mLastFolder.exists()) {
                mLastFolder.mkdirs();
                status = 0;
            } else {
                status = 1;
            }
            mLastFolder = null;
        } catch (Exception e) {
            e.printStackTrace();
            status = -1;
        }
        return status;
    }
}
